package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.company;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.config.SzConfig;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompeteExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CpyContractExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CpyContractExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysFilesService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.TCpyContractService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.TCpyFilesService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.TCpyContractVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.TCpyFileVo;
import com.xiaoxu.intranetweb.util.FileUploadUtils;
import com.xiaoxu.intranetweb.util.SzResult;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;

@Component
@Slf4j
public class ContractBu {
    @Autowired
    private TCpyContractService cpyContractService;
    @Autowired
    UserInfoDao userInfoDao;
    @Autowired
    ISysFilesService  iSysFilesService;
    @Autowired
    TCpyFilesService tCpyFilesService;

    //合同管理
    public SzResult getCpyContract(String cpyId, String startTime, String endTime, String contractName, String plantId) {
        List<TCpyContractVo> list = cpyContractService.cpyContractVoList(cpyId, startTime, endTime, contractName, plantId);
        return SzResult.success(list);
    }

    //文件管理
    public SzResult getCpyFile(String cpyContractId) {
        List<TCpyFileVo> list = cpyContractService.cpyFileList(cpyContractId);
        return SzResult.success(list);
    }

//新增合同
    public SzResult addCpyContract(String contractName,String cpyId,String StartTime,String EndTime,String remark,String token,String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //单位不能重复
        TCpyContract tCpyContract = new TCpyContract();
        tCpyContract.setContractName(contractName);
        tCpyContract.setContractCpyId(cpyId);
        tCpyContract.setContractStartTime(StartTime);
        tCpyContract.setContractEndTime(EndTime);
        tCpyContract.setContractRemark(remark);
        tCpyContract.setContractCreateUser(user.getUserName());
        tCpyContract.setContractCreateTime(String.valueOf(LocalDateTime.now()).replace("T"," "));
        tCpyContract.setDataFrom(plantId);
        cpyContractService.save(tCpyContract);
        return SzResult.success(tCpyContract.getId());
    }

    //上传文件
    public SzResult uploadFile(MultipartFile file, String connId, String token) throws Exception {
        //存储文件返回绝对路径
        String filePath = FileUploadUtils.upload(SzConfig.getUploadPath(),file);
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        TCpyFiles tCpyFiles = new TCpyFiles();
        tCpyFiles.setConnId(connId);
        tCpyFiles.setUploadFrom(StpUtil.getLoginIdByToken(token).toString());
        tCpyFiles.setFileName(fileName);
        tCpyFiles.setFilePath(filePath);
        tCpyFiles.setFileSize(String.valueOf(file.getSize()));
        tCpyFiles.setFileType(suffix.replace(".", ""));
        tCpyFiles.setUploadTime(String.valueOf(LocalDateTime.now()).replace("T"," "));
        tCpyFilesService.save(tCpyFiles);
        return SzResult.Success();
    }

    //下载文件
    public TCpyFiles downloadFile(String id) {
//        根据id区数据库中查询文件信息
        QueryWrapper<TCpyFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        return tCpyFilesService.getOne(queryWrapper);
    }
    //删除文件
    public SzResult deleteFile(String id) {
        QueryWrapper<TCpyFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TCpyFiles tCpyFiles = tCpyFilesService.getOne(queryWrapper);
        File file = new File(tCpyFiles.getFilePath() + tCpyFiles.getId() + "." + tCpyFiles.getFileType());
        if (file.exists()) {
            file.delete();
        }
        tCpyFilesService.remove(queryWrapper);
        return SzResult.Success();
    }

    //删除合同
    public SzResult deleteContract(String id) {
        QueryWrapper<TCpyContract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TCpyContract tCpyContract = cpyContractService.getOne(queryWrapper);
        cpyContractService.remove(queryWrapper);
        return SzResult.Success();
    }

    //合同修改
    public SzResult updateCpyContract(String id,String contractName,String cpyId,String StartTime,String EndTime,String remark,String token) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        TCpyContract tCpyContract = new TCpyContract();
        tCpyContract.setId(id);
        tCpyContract.setContractName(contractName);
        tCpyContract.setContractCpyId(cpyId);
        tCpyContract.setContractStartTime(StartTime);
        tCpyContract.setContractEndTime(EndTime);
        tCpyContract.setContractRemark(remark);
        tCpyContract.setContractAlterUser(user.getUserName());
        tCpyContract.setContractAlterTime(String.valueOf(LocalDateTime.now()).replace("T"," "));
        cpyContractService.updateById(tCpyContract);
        return SzResult.Success();
    }


    //导出合同excel
    @Async
    public Future<List<CpyContractExcelEn>> exportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean isHeader,
                                                        String mode, Boolean original, Map<String, String> pager, String sheetName, String token,  String cpyId,String startTime,String endTime ,String contractName,String plantId) throws Exception {
        // String plantId = one2.getPlantId();
        List<Map<String, Object>> newIds = new ArrayList<>();
        List<CpyContractExcelEn> cpyContractExcelEns = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    //导出当前页
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            Object object = field.get("field");//获得的是field对应的值
                            if (id.containsKey(object)) {
                                newId.put(object.toString(), id.get(object));
                            }
                        }
                        newIds.add(newId);
                    }

                    for (Map<String, Object> stringObjectMap : newIds) {
                        CpyContractExcelEn cpyContractExcelEn = CpyContractExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {

                            if (entry.getKey().equals("cpyCo")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setCo("");
                                } else {
                                    cpyContractExcelEn.setCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("contractName")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setContractName("");
                                } else {
                                    cpyContractExcelEn.setContractName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("contractStartTime")) {
                                   if (entry.getValue() == null || entry.getValue().equals("")) {
                                        cpyContractExcelEn.setContractStartTime("");
                                    } else {
                                        cpyContractExcelEn.setContractStartTime(entry.getValue().toString());
                                    }
                            }
                            if (entry.getKey().equals("contractEndTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setContractEndTime("");
                                } else {
                                    cpyContractExcelEn.setContractEndTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createUser")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setCreatUser("");
                                } else {
                                    cpyContractExcelEn.setCreatUser(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("alterUser")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setAlterUser("");
                                } else {
                                    cpyContractExcelEn.setAlterUser(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("alterTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setAlterTime("");
                                } else {
                                    cpyContractExcelEn.setAlterTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("contractRemark")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setContractRemark("");
                                } else {
                                    cpyContractExcelEn.setContractRemark(entry.getValue().toString());
                                }
                            }

                        }
                        cpyContractExcelEns.add(cpyContractExcelEn);
                    }
                    break;
                case "all":
                    //导出全部
                    List<TCpyContractVo> list = cpyContractService.cpyContractVoList(cpyId, startTime, endTime, contractName, plantId);
                    for (TCpyContractVo tCpyContractVo : list) {
                        CpyContractExcelEn cpyContractExcelEn = CpyContractExcelEn.builder()
                                .co(Optional.of(tCpyContractVo.getCo()+"."+tCpyContractVo.getChiCo()).orElse(""))
                                .contractName(Optional.ofNullable(tCpyContractVo.getContractName()).orElse(""))
                                .contractStartTime(Optional.of(String.valueOf(tCpyContractVo.getContractStartTime()).replace("T"," ")).orElse(""))
                                .contractEndTime(Optional.of(String.valueOf(tCpyContractVo.getContractEndTime()).replace("T"," ")).orElse(""))
                                .creatUser(Optional.ofNullable(tCpyContractVo.getCreateUser()).orElse(""))
                                .alterUser(Optional.ofNullable(tCpyContractVo.getAlterUser()).orElse(""))
                                .alterTime(Optional.of(String.valueOf(tCpyContractVo.getAlterTime()).replace("T"," ")).orElse(""))
                                .contractRemark(Optional.ofNullable(tCpyContractVo.getContractRemark()).orElse(""))
                                .build();
                        cpyContractExcelEns.add(cpyContractExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
                    for (Map<String, Object> newId : newIds) {
                        CpyContractExcelEn cpyContractExcelEn = CpyContractExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("cpyCo")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setCo("");
                                } else {
                                    cpyContractExcelEn.setCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("contractName")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setContractName("");
                                } else {
                                    cpyContractExcelEn.setContractName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("contractStartTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setContractStartTime("");
                                } else {
                                    cpyContractExcelEn.setContractStartTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("contractEndTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setContractEndTime("");
                                } else {
                                    cpyContractExcelEn.setContractEndTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createUser")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setCreatUser("");
                                } else {
                                    cpyContractExcelEn.setCreatUser(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("alterUser")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setAlterUser("");
                                } else {
                                    cpyContractExcelEn.setAlterUser(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("alterTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setAlterTime("");
                                } else {
                                    cpyContractExcelEn.setAlterTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("contractRemark")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    cpyContractExcelEn.setContractRemark("");
                                } else {
                                    cpyContractExcelEn.setContractRemark(entry.getValue().toString());
                                }
                            }
                        }
                        cpyContractExcelEns.add(cpyContractExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(cpyContractExcelEns);
    }
}
